<script setup>
import {reactive,watch,watchEffect,computed,ref} from "vue"

const person = reactive({
    firstName:"Sun",
    lastName:"WuKong"
})

// 计算属性 只有getter
const fullName1 = computed(() => `${person.firstName}-${person.lastName}`)
// 计算属性 getter setter
const fullName2 = computed({
    set(value){
        // 当他改变的时候，其他数据的变化
        const [firstName,lastName] = value.split("-")
        person.firstName = firstName
        person.lastName = lastName
    },
    get(){
        return `${person.firstName}-${person.lastName}`
    }
})
// 属性监视
const fullName3 = ref("")
// 监视整个对象
watch(person,(value,oldValue) => {
    console.log("watch person",value,oldValue);
    fullName3.value = `${value.firstName}-${value.lastName}`
},{deep:true,immediate:true}) // 深度监视并立即监视

// 监视fullName3
watch(fullName3,newValue => {
    console.log("watch fullName3",newValue);
    const [firstName,lastName] = newValue.split("-")
    person.firstName = firstName
    person.lastName = lastName
},{deep:true,immediate:true})
// 监视多个属性
watch([() => person.firstName,() => person.lastName, fullName3], (values) => {
    console.log("watch多个值",values);
})

// 监听所有回调中使用的数据
watchEffect(() => {
    // 在当前回调中使用的数据都会被监听
    console.log("回调中使用的数据",person.firstName,fullName3.value);
})
</script>

<template>
    <h2>姓名</h2>
    <span>firstName</span><input v-model="person.firstName" type="text">
    <span>lastName</span><input v-model="person.lastName" type="text">
    <span>fullName1</span><input v-model="fullName1" type="text">
    <span>fullName2</span><input v-model="fullName2" type="text">
    <span>fullName3</span><input v-model="fullName3" type="text">
</template>

